<template>
  <div class="work-order-config page-container">
    <div class="page-header">
      <h2>工单配置</h2>
    </div>

    <el-tabs v-model="activeTab" class="config-tabs">
      <!-- 基础数据字段管理 -->
      <el-tab-pane label="基础数据字段" name="basic">
        <div class="tab-header">
          <div class="tab-title">
            <h3>基础数据字段管理</h3>
            <p class="tab-description">管理工单的基础数据字段显示、必填状态和排序</p>
          </div>
          <div class="tab-actions">
            <el-button type="success" @click="saveBasicConfig" :loading="savingBasic">
              <el-icon><Check /></el-icon>
              保存基础配置
            </el-button>
          </div>
        </div>

        <el-card class="basic-fields-card">
          <template #header>
            <div class="card-header">
              <span>基础字段配置</span>
              <span class="field-count">共 {{ basicFields.length }} 个基础字段</span>
            </div>
          </template>

          <el-table :data="basicFields" stripe style="width: 100%" v-loading="loadingBasic">
            <el-table-column label="字段名称" prop="label" min-width="150">
              <template #default="{ row }">
                <div class="field-info">
                  <strong>{{ row.label }}</strong>
                  <div class="field-key">{{ row.key }}</div>
                </div>
              </template>
            </el-table-column>

            <el-table-column label="字段类型" prop="type" width="120">
              <template #default="{ row }">
                <el-tag :type="getBasicFieldTypeColor(row.type)" size="small">
                  {{ getBasicFieldTypeLabel(row.type) }}
                </el-tag>
              </template>
            </el-table-column>

            <el-table-column label="是否显示" width="100">
              <template #default="{ row }">
                <el-switch
                  v-model="row.visible"
                  size="small"
                />
              </template>
            </el-table-column>

            <el-table-column label="是否必填" width="100">
              <template #default="{ row }">
                <el-switch
                  v-model="row.required"
                  size="small"
                  :disabled="row.system_required"
                />
              </template>
            </el-table-column>

            <el-table-column label="显示顺序" width="120">
              <template #default="{ row, $index }">
                <div class="sort-controls">
                  <el-button
                    size="small"
                    :disabled="$index === 0"
                    @click="moveBasicField($index, 'up')"
                  >
                    ↑
                  </el-button>
                  <span class="sort-number">{{ $index + 1 }}</span>
                  <el-button
                    size="small"
                    :disabled="$index === basicFields.length - 1"
                    @click="moveBasicField($index, 'down')"
                  >
                    ↓
                  </el-button>
                </div>
              </template>
            </el-table-column>

            <el-table-column label="数据编辑" min-width="300">
              <template #default="{ row, $index }">
                <div v-if="row.type === 'select'" class="options-edit">
                  <div v-if="!row.isEditingOptions" class="options-display">
                    <!-- 显示当前选项状态 -->
                    <div class="options-status">
                      <div class="current-options">
                        <el-text size="small" type="primary">当前选项 ({{ row.options.length }}):</el-text>
                        <div class="option-tags">
                          <el-tag
                            v-for="(option, idx) in row.options"
                            :key="idx"
                            size="small"
                            class="option-tag"
                            :type="idx % 2 === 0 ? 'primary' : 'success'"
                          >
                            {{ option }}
                          </el-tag>
                        </div>
                      </div>
                      <!-- 显示原始数据信息 -->
                      <div v-if="row.originalOptions && row.originalOptions.length > 0" class="original-info">
                        <el-text size="small" type="info">
                          <el-icon><InfoFilled /></el-icon>
                          检测到API原始数据，已自动处理显示
                        </el-text>
                      </div>
                    </div>
                    <el-button
                      size="small"
                      type="primary"
                      link
                      @click="startEditOptions($index)"
                    >
                      <el-icon><Edit /></el-icon>
                      编辑选项
                    </el-button>
                  </div>
                  <div v-else class="options-edit-form">
                    <div class="edit-hint">
                      <el-text size="small" type="info">
                        <el-icon><InfoFilled /></el-icon>
                        编辑选项显示文本，多个选项用逗号分隔
                      </el-text>
                      <div v-if="row.originalOptions && row.originalOptions.length > 0" class="original-data-hint">
                        <el-text size="small" type="warning">
                          原始API数据: {{ row.originalOptions.slice(0, 3).join(', ') }}{{ row.originalOptions.length > 3 ? '...' : '' }}
                        </el-text>
                      </div>
                    </div>
                    <el-input
                      v-model="row.optionsText"
                      placeholder="请输入选项显示文本，逗号分隔（如：维修,清洁,检查）"
                      size="small"
                      class="options-input"
                      type="textarea"
                      :rows="3"
                    />
                    <div class="edit-actions">
                      <el-button
                        size="small"
                        type="success"
                        @click="saveOptions($index)"
                      >
                        <el-icon><Check /></el-icon>
                        保存
                      </el-button>
                      <el-button
                        size="small"
                        type="info"
                        @click="cancelEditOptions($index)"
                      >
                        <el-icon><Close /></el-icon>
                        取消
                      </el-button>
                    </div>
                  </div>
                </div>
                <span v-else class="no-options">-</span>
              </template>
            </el-table-column>

            <el-table-column label="描述" prop="description" min-width="200">
              <template #default="{ row }">
                <span class="field-description">{{ row.description }}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-tab-pane>

      <!-- 自定义字段管理 -->
      <el-tab-pane label="自定义字段" name="custom">
        <div class="tab-header">
          <div class="tab-title">
            <h3>自定义字段管理</h3>
            <p class="tab-description">创建和管理工单的自定义字段</p>
          </div>
          <div class="tab-actions">
            <el-button type="primary" @click="addField">
              <el-icon><Plus /></el-icon>
              添加字段
            </el-button>
            <el-button type="success" @click="saveConfig" :loading="saving">
              <el-icon><Check /></el-icon>
              保存配置
            </el-button>
            <el-button type="info" @click="exportConfig">
              导出配置
            </el-button>
            <el-upload
              class="upload-btn"
              :show-file-list="false"
              :before-upload="beforeUpload"
              :on-change="handleImport"
              accept=".json"
            >
              <el-button type="warning">导入配置</el-button>
            </el-upload>
          </div>
        </div>

        <!-- 自定义字段列表 -->
        <el-card class="fields-card">
          <template #header>
            <div class="card-header">
              <span>自定义字段配置</span>
              <span class="field-count">共 {{ fields.length }} 个字段</span>
            </div>
          </template>

      <el-table :data="fields" stripe style="width: 100%" v-loading="loading">
        <el-table-column label="操作" width="180" fixed="left">
          <template #default="{ row, $index }">
            <div class="action-buttons">
              <el-button
                v-if="!row.isEditing"
                type="primary"
                size="small"
                @click="toggleEditField($index)"
              >
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <el-button
                v-if="row.isEditing"
                type="success"
                size="small"
                @click="saveField($index)"
              >
                <el-icon><Check /></el-icon>
                保存
              </el-button>
              <el-button
                v-if="row.isEditing"
                type="info"
                size="small"
                @click="cancelEdit($index)"
              >
                <el-icon><Close /></el-icon>
                取消
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="removeField($index)"
              >
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="name" label="字段名称" min-width="150">
          <template #default="{ row, $index }">
            <el-input
              v-if="row.isEditing"
              v-model="row.name"
              placeholder="请输入字段名称"
              size="small"
            />
            <span v-else>{{ row.name || '未命名字段' }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="field_type" label="字段类型" width="150">
          <template #default="{ row, $index }">
            <el-select
              v-if="row.isEditing"
              v-model="row.field_type"
              placeholder="请选择字段类型"
              @change="onFieldTypeChange($index)"
              size="small"
              style="width: 100%"
            >
              <el-option label="文字" value="text" />
              <el-option label="单选" value="select" />
              <el-option label="多选" value="checkbox" />
              <el-option label="日期时间" value="datetime" />
            </el-select>
            <el-tag v-else :type="getFieldTypeColor(row.field_type)">
              {{ getFieldTypeLabel(row.field_type) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="optionsText" label="选项配置" min-width="200">
          <template #default="{ row, $index }">
            <el-input
              v-if="row.isEditing && (row.field_type === 'select' || row.field_type === 'checkbox')"
              v-model="row.optionsText"
              placeholder="请输入选项，逗号分隔"
              size="small"
            />
            <el-input
              v-else-if="row.isEditing && row.field_type === 'datetime'"
              v-model="row.dateFormat"
              placeholder="日期格式：YY/MM/DD hh:mm"
              size="small"
              disabled
            />
            <span v-else-if="row.field_type === 'select' || row.field_type === 'checkbox'">
              {{ row.optionsText || '无选项' }}
            </span>
            <span v-else-if="row.field_type === 'datetime'">
              格式：YY/MM/DD hh:mm
            </span>
            <span v-else>-</span>
          </template>
        </el-table-column>

        <el-table-column prop="required" label="是否必填" width="100">
          <template #default="{ row, $index }">
            <el-switch
              v-if="row.isEditing"
              v-model="row.required"
              size="small"
            />
            <el-tag v-else :type="row.required ? 'danger' : 'info'" size="small">
              {{ row.required ? '必填' : '选填' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="placeholder" label="提示文字" min-width="150">
          <template #default="{ row, $index }">
            <el-input
              v-if="row.isEditing"
              v-model="row.placeholder"
              placeholder="请输入提示文字"
              size="small"
            />
            <span v-else>{{ row.placeholder || '-' }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="created_at" label="创建时间" width="150">
          <template #default="{ row }">
            <span v-if="row.id">{{ formatDate(row.created_at) }}</span>
            <el-tag v-else type="warning" size="small">新建</el-tag>
          </template>
        </el-table-column>
      </el-table>

          <div v-if="fields.length === 0" class="empty-state">
            <el-empty description="暂无自定义字段">
              <el-button type="primary" @click="addField">
                <el-icon><Plus /></el-icon>
                添加第一个字段
              </el-button>
            </el-empty>
          </div>
        </el-card>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Check,
  Edit,
  Delete,
  Close,
  InfoFilled
} from '@element-plus/icons-vue'
import { workOrdersApi } from '@/api'

interface Field {
  id: number | null
  name: string
  field_type: string
  optionsText: string
  isEditing: boolean
  required: boolean
  placeholder: string
  dateFormat: string
  sort_id: number | null
  created_at?: string
  options?: string[]
  originalData?: any // 用于取消编辑时恢复数据
}

interface BasicField {
  key: string
  label: string
  type: string
  visible: boolean
  required: boolean
  system_required: boolean
  description: string
  sort_order: number
  options: string[]
  optionsText: string
  isEditingOptions: boolean
  originalOptionsText?: string
}

const activeTab = ref('basic')
const fields = ref<Field[]>([])
const loading = ref(false)
const saving = ref(false)
const loadingBasic = ref(false)
const savingBasic = ref(false)

// 基础数据字段配置 - 从后端动态加载
const basicFields = ref<BasicField[]>([])

// 基础字段管理方法
const getBasicFieldTypeLabel = (type: string) => {
  const typeMap: Record<string, string> = {
    text: '文本',
    textarea: '多行文本',
    select: '下拉选择',
    datetime: '日期时间',
    number: '数字'
  }
  return typeMap[type] || type
}

const getBasicFieldTypeColor = (type: string) => {
  const colorMap: Record<string, string> = {
    text: 'primary',
    textarea: 'success',
    select: 'warning',
    datetime: 'info',
    number: 'danger'
  }
  return colorMap[type] || 'default'
}

const moveBasicField = (index: number, direction: 'up' | 'down') => {
  const newIndex = direction === 'up' ? index - 1 : index + 1
  if (newIndex >= 0 && newIndex < basicFields.value.length) {
    const temp = basicFields.value[index]
    basicFields.value[index] = basicFields.value[newIndex]
    basicFields.value[newIndex] = temp
    
    // 更新排序顺序
    basicFields.value.forEach((field, idx) => {
      field.sort_order = idx + 1
    })
  }
}

// 基础字段选项编辑方法
const startEditOptions = (index: number) => {
  const field = basicFields.value[index]
  field.isEditingOptions = true
  // 保存原始选项文本，用于取消时恢复
  field.originalOptionsText = field.optionsText
}

const saveOptions = (index: number) => {
  const field = basicFields.value[index]
  if (!field.optionsText.trim()) {
    ElMessage.error('选项不能为空')
    return
  }
  
  // 验证选项格式
  const newOptions = field.optionsText.split(',').map(opt => opt.trim()).filter(opt => opt)
  if (newOptions.length === 0) {
    ElMessage.error('请输入有效的选项')
    return
  }
  
  // 更新选项数组
  field.options = newOptions
  field.isEditingOptions = false
  delete field.originalOptionsText
  
  ElMessage.success(`选项更新成功（共${newOptions.length}个选项），请保存基础配置以生效`)
}

const cancelEditOptions = (index: number) => {
  const field = basicFields.value[index]
  // 恢复原始选项文本
  if (field.originalOptionsText !== undefined) {
    field.optionsText = field.originalOptionsText
    delete field.originalOptionsText
  }
  field.isEditingOptions = false
}

const saveBasicConfig = async () => {
  savingBasic.value = true
  try {
    // 调用API保存基础字段配置
    const payload = {
      fields: basicFields.value.map(field => ({
        name: field.key,
        label: field.label,
        field_type: field.type,
        is_visible: field.visible,
        is_required: field.required,
        system_required: field.system_required,
        description: field.description,
        sort_order: field.sort_order,
        field_category: 'basic',
        options: JSON.stringify(field.options)
      }))
    }
    
    await workOrdersApi.updateBasicFieldsConfig(payload)
    
    // 同时保存到本地存储作为备份
    const config = {
      basicFields: basicFields.value.map(field => ({
        key: field.key,
        visible: field.visible,
        required: field.required,
        sort_order: field.sort_order,
        options: field.options,
        optionsText: field.optionsText
      }))
    }
    localStorage.setItem('workOrderBasicFieldsConfig', JSON.stringify(config))
    
    ElMessage.success('基础字段配置保存成功')
  } catch (error: any) {
    console.error('保存基础字段配置失败:', error)
    ElMessage.error('保存基础字段配置失败')
  } finally {
    savingBasic.value = false
  }
}

const loadBasicConfig = async () => {
  loadingBasic.value = true
  try {
    const response = await workOrdersApi.getCustomFields({ field_category: 'basic' })
    if (response.data.fields && response.data.fields.length > 0) {
      basicFields.value = response.data.fields.map((field: any) => {
        // 处理选项数据格式
        let options = []
        let optionsText = ''
        let originalOptions = []
        
        if (field.options && Array.isArray(field.options)) {
          if (field.options.length > 0) {
            // 保存原始选项数据
            originalOptions = [...field.options]
            
            // 检查是否为对象格式 {label, value}
            if (typeof field.options[0] === 'object' && field.options[0].label !== undefined) {
              // 如果是对象格式，提取label作为显示文本
              options = field.options.map((opt: any) => opt.label || opt.value || opt)
              optionsText = options.join(',')
            } else {
              // 如果是字符串数组，直接使用
              options = field.options
              optionsText = field.options.join(',')
            }
          }
        }
        
        return {
          key: field.name,
          label: field.label,
          type: field.field_type,
          visible: field.is_visible,
          required: field.is_required,
          system_required: field.system_required || false,
          description: field.description,
          sort_order: field.sort_order,
          options: options,
          optionsText: optionsText,
          originalOptions: originalOptions,
          isEditingOptions: false
        }
      })
      // 按排序顺序重新排列
      basicFields.value.sort((a, b) => a.sort_order - b.sort_order)
    } else {
      // 如果后端没有数据，使用默认配置
      basicFields.value = [
        {
          key: 'order_number',
          label: '工单编号',
          type: 'text',
          visible: true,
          required: true,
          system_required: true,
          description: '系统自动生成的唯一工单编号',
          sort_order: 1,
          options: [],
          optionsText: '',
          originalOptions: [],
          isEditingOptions: false
        },
        {
          key: 'title',
          label: '工单标题',
          type: 'text',
          visible: true,
          required: false,
          system_required: false,
          description: '工单的标题或简要描述',
          sort_order: 2,
          options: [],
          optionsText: '',
          originalOptions: [],
          isEditingOptions: false
        },
        {
          key: 'description',
          label: '工单描述',
          type: 'textarea',
          visible: true,
          required: false,
          system_required: false,
          description: '工单的详细描述信息',
          sort_order: 3,
          options: [],
          optionsText: '',
          originalOptions: [],
          isEditingOptions: false
        },
        {
          key: 'type',
          label: '工单类型',
          type: 'select',
          visible: true,
          required: true,
          system_required: true,
          description: '工单的类型分类（维修、清洁、安全等）',
          sort_order: 4,
          options: ['维修', '清洁', '安全检查', '设备巡检', '其他'],
          optionsText: '维修,清洁,安全检查,设备巡检,其他',
          originalOptions: [],
          isEditingOptions: false
        },
        {
          key: 'priority',
          label: '优先级',
          type: 'select',
          visible: true,
          required: true,
          system_required: true,
          description: '工单的优先级（低、中、高、紧急）',
          sort_order: 5,
          options: ['低', '中', '高', '紧急'],
          optionsText: '低,中,高,紧急',
          originalOptions: [],
          isEditingOptions: false
        },
        {
          key: 'status',
          label: '工单状态',
          type: 'select',
          visible: true,
          required: true,
          system_required: true,
          description: '工单当前的处理状态',
          sort_order: 6,
          options: ['待接单', '处理中', '已完成', '已取消'],
          optionsText: '待接单,处理中,已完成,已取消',
          originalOptions: [],
          isEditingOptions: false
        },
        {
          key: 'location',
          label: '位置信息',
          type: 'text',
          visible: true,
          required: false,
          system_required: false,
          description: '工单相关的位置或地点',
          sort_order: 7,
          options: [],
          optionsText: '',
          originalOptions: [],
          isEditingOptions: false
        },
        {
          key: 'assignee_id',
          label: '分配人员',
          type: 'select',
          visible: true,
          required: false,
          system_required: false,
          description: '负责处理工单的人员',
          sort_order: 8,
          options: [],
          optionsText: '',
          originalOptions: [],
          isEditingOptions: false
        },
        {
          key: 'area_id',
          label: '所属区域',
          type: 'select',
          visible: true,
          required: false,
          system_required: false,
          description: '工单所属的区域',
          sort_order: 9,
          options: [],
          optionsText: '',
          originalOptions: [],
          isEditingOptions: false
        },
        {
          key: 'scheduled_start',
          label: '计划开始时间',
          type: 'datetime',
          visible: true,
          required: false,
          system_required: false,
          description: '计划开始处理工单的时间',
          sort_order: 10,
          options: [],
          optionsText: '',
          originalOptions: [],
          isEditingOptions: false
        },
        {
          key: 'scheduled_end',
          label: '计划结束时间',
          type: 'datetime',
          visible: true,
          required: false,
          system_required: false,
          description: '计划完成工单的时间',
          sort_order: 11,
          options: [],
          optionsText: '',
          originalOptions: [],
          isEditingOptions: false
        },
        {
          key: 'notes',
          label: '备注信息',
          type: 'textarea',
          visible: true,
          required: false,
          system_required: false,
          description: '工单的额外备注信息',
          sort_order: 12,
          options: [],
          optionsText: '',
          originalOptions: [],
          isEditingOptions: false
        }
      ]
      
      // 尝试从本地存储加载保存的配置
      const savedConfig = localStorage.getItem('workOrderBasicFieldsConfig')
      if (savedConfig) {
        const config = JSON.parse(savedConfig)
        if (config.basicFields) {
          // 合并保存的配置到默认配置
          config.basicFields.forEach((savedField: any) => {
            const field = basicFields.value.find(f => f.key === savedField.key)
            if (field) {
              field.visible = savedField.visible
              field.required = savedField.required
              field.sort_order = savedField.sort_order
              if (savedField.options) {
                field.options = savedField.options
                field.optionsText = savedField.optionsText || savedField.options.join(',')
              }
            }
          })
          
          // 按排序顺序重新排列
          basicFields.value.sort((a, b) => a.sort_order - b.sort_order)
        }
      }
    }
    console.log('基础字段配置加载成功', basicFields.value)
  } catch (error) {
    console.error('加载基础字段配置失败:', error)
    ElMessage.error('加载基础字段配置失败')
    
    // 发生错误时，使用默认配置
    basicFields.value = [
      {
        key: 'order_number',
        label: '工单编号',
        type: 'text',
        visible: true,
        required: true,
        system_required: true,
        description: '系统自动生成的唯一工单编号',
        sort_order: 1,
        options: [],
        optionsText: '',
        originalOptions: [],
        isEditingOptions: false
      },
      {
        key: 'type',
        label: '工单类型',
        type: 'select',
        visible: true,
        required: true,
        system_required: true,
        description: '工单的类型分类',
        sort_order: 4,
        options: ['维修', '清洁', '安全检查', '设备巡检', '其他'],
        optionsText: '维修,清洁,安全检查,设备巡检,其他',
        originalOptions: [],
        isEditingOptions: false
      },
      {
        key: 'priority',
        label: '优先级',
        type: 'select',
        visible: true,
        required: true,
        system_required: true,
        description: '工单的优先级',
        sort_order: 5,
        options: ['低', '中', '高', '紧急'],
        optionsText: '低,中,高,紧急',
        originalOptions: [],
        isEditingOptions: false
      },
      {
        key: 'status',
        label: '工单状态',
        type: 'select',
        visible: true,
        required: true,
        system_required: true,
        description: '工单当前的处理状态',
        sort_order: 6,
        options: ['待接单', '处理中', '已完成', '已取消'],
        optionsText: '待接单,处理中,已完成,已取消',
        originalOptions: [],
        isEditingOptions: false
      }
    ]
    
    // 尝试从本地存储加载
    try {
      const savedConfig = localStorage.getItem('workOrderBasicFieldsConfig')
      if (savedConfig) {
        const config = JSON.parse(savedConfig)
        if (config.basicFields) {
          config.basicFields.forEach((savedField: any) => {
            const field = basicFields.value.find(f => f.key === savedField.key)
            if (field) {
              field.visible = savedField.visible
              field.required = savedField.required
              field.sort_order = savedField.sort_order
              if (savedField.options) {
                field.options = savedField.options
                field.optionsText = savedField.optionsText || savedField.options.join(',')
              }
            }
          })
          basicFields.value.sort((a, b) => a.sort_order - b.sort_order)
        }
      }
    } catch (localError) {
      console.error('从本地存储加载配置也失败:', localError)
    }
  } finally {
    loadingBasic.value = false
  }
}


// 加载现有字段
const loadFields = async () => {
  loading.value = true
  try {
    const response = await workOrdersApi.getCustomFields({ field_category: 'custom' })
    fields.value = response.data.fields.map((field: any) => ({
      id: field.id,
      name: field.name,
      field_type: field.field_type,
      optionsText: field.options ? field.options.join(',') : '',
      required: field.is_required || false,
      placeholder: field.placeholder || '',
      sort_id: field.sort_order || null,
      dateFormat: 'YY/MM/DD hh:mm',
      created_at: field.created_at,
      isEditing: false,
      options: field.options
    }))
    // 按sort_id排序，sort_id越小越靠前
    fields.value.sort((a, b) => {
      if (a.sort_id === null) return 1
      if (b.sort_id === null) return -1
      return a.sort_id - b.sort_id
    })
  } catch (error: any) {
    console.error('加载字段失败:', error)
    ElMessage.error('加载字段失败')
  } finally {
    loading.value = false
  }
}

const addField = () => {
  fields.value.push({
    id: null,
    name: '',
    field_type: 'text',
    optionsText: '',
    required: false,
    placeholder: '',
    sort_id: fields.value.length > 0 ? Math.max(...fields.value.map(f => f.sort_id || 0)) + 1 : 1,
    dateFormat: 'YY/MM/DD hh:mm',
    isEditing: true
  })
}

const removeField = async (index: number) => {
  const field = fields.value[index]
  
  try {
    await ElMessageBox.confirm(
      `确定要删除字段 "${field.name || '未命名字段'}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    if (field.id) {
      await workOrdersApi.deleteCustomField(field.id)
      ElMessage.success('字段删除成功')
    }
    fields.value.splice(index, 1)
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('删除字段失败')
    }
  }
}

const onFieldTypeChange = (index: number) => {
  const field = fields.value[index]
  if (field.field_type === 'datetime') {
    field.optionsText = ''
    field.dateFormat = 'YY/MM/DD hh:mm'
  } else if (field.field_type !== 'select' && field.field_type !== 'checkbox') {
    field.optionsText = ''
    field.dateFormat = ''
  }
}

const toggleEditField = (index: number) => {
  const field = fields.value[index]
  if (!field.isEditing) {
    // 开始编辑，保存原始数据
    field.originalData = {
      name: field.name,
      field_type: field.field_type,
      optionsText: field.optionsText,
      required: field.required,
      placeholder: field.placeholder,
      dateFormat: field.dateFormat
    }
  }
  field.isEditing = !field.isEditing
}

const cancelEdit = (index: number) => {
  const field = fields.value[index]
  if (field.originalData) {
    // 恢复原始数据
    Object.assign(field, field.originalData)
    delete field.originalData
  }
  field.isEditing = false
}

const saveField = async (index: number) => {
  const field = fields.value[index]
  
  // 验证字段名称
  if (!field.name.trim()) {
    ElMessage.error('字段名称不能为空')
    return
  }
  
  try {
    const payload = {
      name: field.name.trim(),
      label: field.name.trim(),
      field_type: field.field_type,
      is_required: field.required,
      placeholder: field.placeholder,
      sort_order: field.sort_id || null,
      options: field.optionsText ? field.optionsText.split(',').map(opt => opt.trim()).filter(opt => opt) : []
    }
    
    if (field.id) {
      // 更新现有字段
      const response = await workOrdersApi.updateCustomField(field.id, payload)
      Object.assign(field, {
        ...response.data.field,
        optionsText: response.data.field.options ? response.data.field.options.join(',') : '',
        dateFormat: field.field_type === 'datetime' ? 'YY/MM/DD hh:mm' : '',
        isEditing: false
      })
    } else {
      // 创建新字段
      const response = await workOrdersApi.createCustomField(payload)
      Object.assign(field, {
        ...response.data.field,
        optionsText: response.data.field.options ? response.data.field.options.join(',') : '',
        dateFormat: field.field_type === 'datetime' ? 'YY/MM/DD hh:mm' : '',
        isEditing: false
      })
    }
    
    delete field.originalData
    ElMessage.success(field.id ? '字段更新成功' : '字段创建成功')
  } catch (error: any) {
    const msg = error?.response?.data?.error || error.message || '保存字段失败'
    ElMessage.error(msg)
    console.error('保存字段失败:', error)
  }
}

// 页面加载时获取现有字段和基础配置
onMounted(() => {
  loadFields()
  loadBasicConfig()
})

// 导出配置为JSON文件
const exportConfig = () => {
  if (fields.value.length === 0) {
    ElMessage.warning("没有可导出的字段配置")
    return
  }
  const exportData = fields.value.map(field => ({
    name: field.name,
    field_type: field.field_type,
    options: field.optionsText ? field.optionsText.split(",").map(opt => opt.trim()).filter(opt => opt) : [],
    is_required: field.required,
    placeholder: field.placeholder,
    sort_order: field.sort_id
  }))
  const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: "application/json" })
  const url = URL.createObjectURL(blob)
  const a = document.createElement("a")
  a.href = url
  a.download = "work_order_fields.json"
  a.click()
  URL.revokeObjectURL(url)
  ElMessage.success("导出成功")
}

// 导入配置前的校验，阻止自动上传
const beforeUpload = () => {
  return false
}

// 处理导入的JSON文件
const handleImport = (file: any) => {
  const reader = new FileReader()
  reader.onload = (e: any) => {
    try {
      const importedFields = JSON.parse(e.target.result)
      if (!Array.isArray(importedFields)) {
        ElMessage.error("导入文件格式错误，应该是字段数组")
        return
      }
      importedFields.forEach((field: any) => {
        if (field.name && field.field_type) {
          fields.value.push({
            id: null,
            name: field.name,
            field_type: field.field_type,
            optionsText: field.options ? field.options.join(",") : "",
            required: field.is_required || field.required || false,
            placeholder: field.placeholder || "",
            sort_id: field.sort_order || field.sort_id || null,
            dateFormat: field.field_type === "datetime" ? "YY/MM/DD hh:mm" : "",
            isEditing: false
          })
        }
      })
      // 导入后按sort_id排序
      fields.value.sort((a, b) => {
        if (a.sort_id === null) return 1
        if (b.sort_id === null) return -1
        return a.sort_id - b.sort_id
      })
      ElMessage.success("导入成功")
    } catch (error) {
      ElMessage.error("导入文件解析失败")
    }
  }
  reader.readAsText(file.raw)
}



const saveConfig = async () => {
  // 检查是否有正在编辑的字段
  const editingFields = fields.value.filter(field => field.isEditing)
  if (editingFields.length > 0) {
    ElMessage.warning('请先完成正在编辑的字段')
    return
  }
  
  // 检查是否有需要保存的字段（包括新导入的字段）
  const unsavedFields = fields.value.filter(field => !field.id)
  if (fields.value.length === 0) {
    ElMessage.warning('没有需要保存的字段配置')
    return
  }
  
  saving.value = true
  try {
    let savedCount = 0
    let errorCount = 0
    
    // 保存所有未保存的字段
    for (const field of unsavedFields) {
      // 验证字段名称
      if (!field.name.trim()) {
        ElMessage.error(`字段名称不能为空`)
        errorCount++
        continue
      }
      
      try {
        const payload = {
          name: field.name.trim(),
          label: field.name.trim(),
          field_type: field.field_type,
          is_required: field.required,
          placeholder: field.placeholder,
          sort_order: field.sort_id || null,
          options: field.optionsText ? field.optionsText.split(',').map(opt => opt.trim()).filter(opt => opt) : []
        }
        
        const response = await workOrdersApi.createCustomField(payload)
        Object.assign(field, {
          ...response.data.field,
          optionsText: response.data.field.options ? response.data.field.options.join(',') : '',
          dateFormat: field.field_type === 'datetime' ? 'YY/MM/DD hh:mm' : '',
          isEditing: false
        })
        savedCount++
      } catch (error: any) {
        console.error(`保存字段 ${field.name} 失败:`, error)
        errorCount++
      }
    }
    
    if (savedCount > 0) {
      ElMessage.success(`配置已保存，共保存 ${savedCount} 个字段${errorCount > 0 ? `，${errorCount} 个字段保存失败` : ''}`)
    } else if (unsavedFields.length === 0) {
      ElMessage.success('所有字段已保存，无需重复保存')
    } else {
      ElMessage.error('保存失败，请检查字段配置')
    }
  } catch (error: any) {
    const msg = error?.response?.data?.error || error.message || '保存配置失败'
    ElMessage.error(msg)
    console.error('保存配置失败:', error)
  } finally {
    saving.value = false
  }
}

// 辅助方法
const getFieldTypeLabel = (type: string) => {
  const typeMap: Record<string, string> = {
    text: '文字',
    select: '单选',
    checkbox: '多选',
    datetime: '日期时间'
  }
  return typeMap[type] || type
}

const getFieldTypeColor = (type: string) => {
  const colorMap: Record<string, string> = {
    text: 'primary',
    select: 'success',
    checkbox: 'warning',
    datetime: 'info'
  }
  return colorMap[type] || 'default'
}

const formatDate = (dateString: string) => {
  if (!dateString) return '-'
  try {
    const date = new Date(dateString)
    return date.toLocaleDateString('zh-CN', {
      year: '2-digit',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    }).replace(/\//g, '/').replace(',', '')
  } catch {
    return dateString
  }
}
</script>

<style scoped>
.page-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #333;
}

.config-tabs {
  margin-top: 20px;
}

.tab-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
  padding: 0 4px;
}

.tab-title h3 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 18px;
}

.tab-description {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.tab-actions {
  display: flex;
  gap: 10px;
}

.fields-card,
.basic-fields-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.field-count {
  color: #666;
  font-size: 14px;
}

.action-buttons {
  display: flex;
  gap: 5px;
  flex-wrap: wrap;
}

.action-buttons .el-button {
  margin: 0;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table .el-table__cell) {
  padding: 12px 0;
}

:deep(.el-tag) {
  border-radius: 4px;
}

:deep(.el-switch) {
  --el-switch-on-color: #67c23a;
}

.field-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.field-key {
  font-size: 12px;
  color: #999;
  font-family: 'Courier New', monospace;
}

.field-description {
  color: #666;
  font-size: 13px;
  line-height: 1.4;
}

.sort-controls {
  display: flex;
  align-items: center;
  gap: 8px;
}

.sort-controls .el-button {
  padding: 4px 8px;
  font-size: 12px;
  min-height: auto;
}

.sort-number {
  font-weight: bold;
  color: #409eff;
  min-width: 20px;
  text-align: center;
}

.field-item {
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 20px;
  margin-bottom: 15px;
  background-color: #fafafa;
}

.field-item:hover {
  border-color: #c0c4cc;
  background-color: #f5f7fa;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .tab-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .tab-actions {
    width: 100%;
    justify-content: flex-end;
    flex-wrap: wrap;
  }
  
  .action-buttons {
    flex-direction: column;
    width: 100%;
  }
  
  .action-buttons .el-button {
    width: 100%;
    margin-bottom: 5px;
  }
  
  .sort-controls {
    flex-direction: column;
    gap: 4px;
  }
  
  .sort-controls .el-button {
    width: 100%;
  }
}

/* 选项编辑相关样式 */
.options-edit {
  width: 100%;
}

.options-display {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.options-status {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 8px;
}

.current-options {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.option-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.option-tag {
  margin: 0;
  background-color: #f0f9ff;
  border-color: #0ea5e9;
  color: #0369a1;
}

.original-info {
  padding: 6px 10px;
  background-color: #f0f9ff;
  border: 1px solid #bfdbfe;
  border-radius: 4px;
  font-size: 12px;
}

.original-info .el-text {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #1e40af;
}

.original-data-hint {
  padding: 6px 10px;
  background-color: #fef3c7;
  border: 1px solid #fbbf24;
  border-radius: 4px;
  margin-top: 6px;
  font-size: 12px;
  color: #92400e;
}

.options-edit-form {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.edit-hint {
  padding: 8px 12px;
  background-color: #f0f9ff;
  border: 1px solid #bfdbfe;
  border-radius: 4px;
  margin-bottom: 8px;
}

.edit-hint .el-text {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #1e40af;
  font-size: 13px;
}

.edit-hint .el-icon {
  font-size: 14px;
}

.options-input {
  width: 100%;
}

.edit-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-start;
}

.edit-actions .el-button {
  padding: 4px 12px;
  font-size: 12px;
}

.no-options {
  color: #999;
  font-style: italic;
}

/* 选项标签容器 */
.options-display .option-tag:last-of-type {
  margin-right: 0;
}

/* 编辑按钮样式 */
.options-display .el-button {
  margin-top: 4px;
  align-self: flex-start;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .edit-actions {
    flex-direction: column;
  }
  
  .edit-actions .el-button {
    width: 100%;
  }
}
</style>